package cn.tedu.d3_lock;

/*
 测试线程死锁
 出现锁嵌套
 */
public class Test {
    public static void main(String[] args) {
        String lock1="apple";
        String lock2="pear";

        Thread t1=new Thread(){
            public void run(){

                synchronized (lock1) {
                    Thread t = Thread.currentThread();
                    String name = t.getName();
                    System.out.println(name + "开始运行...");

                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {}

                    synchronized (lock2) {
                        System.out.println(name+"获取lock2锁...");
                        try {
                            Thread.sleep(3000);
                        } catch (Exception e) {}
                        System.out.println(name+"释放lock2锁");
                    }
                    System.out.println(name+"运行结束");
                }
            }
        };
        Thread t2=new Thread(){
            public void run(){

                synchronized (lock2){
                    //获取运行该线程任务的线程名
                    Thread t=Thread.currentThread();
                    String name=t.getName();
                    System.out.println(name+"开始运行");

                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) { }
                    //获取lock1
                    synchronized (lock1){
                        System.out.println(name+"获取lock1....");
                        try {
                            Thread.sleep(3000);
                        } catch (Exception e) { }
                        System.out.println(name+"释放lock1");
                    }
                    System.out.println(name+"运行结束");
                }
            }
        };
//        t1.run();//main线程运行
//        t2.run();//main线程运行
        t1.start();
        t2.start();
        System.out.println("over");

    }
}
